{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Mesh generation for tutorial 05"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import gmsh\n",
    "from mpi4py import MPI\n",
    "from dolfinx.io import XDMFFile\n",
    "from multiphenicsx.mesh.utils import gmsh_to_fenicsx"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "assert MPI.COMM_WORLD.size == 1, \"This mesh generation notebook is supposed to be run in serial\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Geometrical parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "r = 3\n",
    "lcar = 1. / 4."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create mesh with gmsh"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gmsh.initialize()\n",
    "gmsh.model.add(\"mesh\")\n",
    "p0 = gmsh.model.geo.addPoint(0.0, 0.0, 0.0, lcar)\n",
    "p1 = gmsh.model.geo.addPoint(0.0, +r, 0.0, lcar)\n",
    "p2 = gmsh.model.geo.addPoint(0.0, -r, 0.0, lcar)\n",
    "c0 = gmsh.model.geo.addCircleArc(p1, p0, p2)\n",
    "c1 = gmsh.model.geo.addCircleArc(p2, p0, p1)\n",
    "curve_loop = gmsh.model.geo.addCurveLoop([c0, c1])\n",
    "circle = gmsh.model.geo.addPlaneSurface([curve_loop])\n",
    "gmsh.model.geo.synchronize()\n",
    "gmsh.model.addPhysicalGroup(1, [c0, c1], 1)\n",
    "gmsh.model.addPhysicalGroup(2, [circle], 0)\n",
    "gmsh.model.mesh.generate(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Convert to a dolfinx mesh"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mesh, subdomains, boundaries = gmsh_to_fenicsx(gmsh.model, gdim=2)\n",
    "gmsh.finalize()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Save mesh and boundaries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with XDMFFile(MPI.COMM_WORLD, \"circle.xdmf\", \"w\") as file:\n",
    "    file.write_mesh(mesh)\n",
    "    mesh.topology.create_connectivity(mesh.topology.dim - 1, mesh.topology.dim)\n",
    "    file.write_meshtags(boundaries)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython"
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
